#include "qmlfile.h"

#include <QtDeclarative/qdeclarative.h>
#include <QDir>
#include <QFileDialog>

QMLFile::QMLFile(QDeclarativeItem *parent):
    QDeclarativeItem(parent)
{
    // By default, QDeclarativeItem does not draw anything. If you subclass
    // QDeclarativeItem to create a visual item, you will need to uncomment the
    // following line:
    
    // setFlag(ItemHasNoContents, false);

    m_operationState = Idle;

    connect(&_fileAcync, SIGNAL(finished(bool)), this, SLOT(asyncFinished(bool)));
}

QMLFile::~QMLFile()
{
}

//存在確認
bool QMLFile::exists(const QString &path)
{
    return QFile::exists(path);
}

//ディレクトリ内のディレクトリリスト
QStringList QMLFile::getEntryList(const QString &path)
{
    QStringList ret;
    QDir dir(path);
    dir.setFilter(QDir::Dirs | QDir::Hidden | QDir::NoSymLinks);
    dir.setSorting(QDir::Size | QDir::Reversed);

    QFileInfoList list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i) {
        QFileInfo fileInfo = list.at(i);
        ret.append(fileInfo.fileName());
    }
    return ret;
}

//フォルダ選択ダイアログ
QString QMLFile::getExistingDirectory(const QString &title, const QString &default_path)
{
    return QFileDialog::getExistingDirectory(NULL, title,
                                             default_path,
                                            QFileDialog::ShowDirsOnly
                                            | QFileDialog::DontResolveSymlinks);
}
//ファイル選択ダイアログ
QString QMLFile::getOpenFileName(const QString &title, const QString &default_path, const QString &filter)
{
    return QFileDialog::getOpenFileName(NULL, title
                                        , default_path
                                        , filter);
}


//ファイルコピー開始
bool QMLFile::copy(const QString &fileName, const QString &newName)
{
    bool ret = false;
    if(m_operationState != Idle){
    }else if(fileName.length() < 1 || newName.length() < 1){
    }else{
        _fileAcync.m_fileName = fileName;
        _fileAcync.m_newName = newName;
        _fileAcync.start();
        ret = true;
    }
    return ret;
}



//コピーなどの状態ステータス
QMLFile::OperationStateType QMLFile::operationState() const
{
    return m_operationState;
}
void QMLFile::setOperationState(const OperationStateType &state)
{
    if(state != m_operationState){
        m_operationState = state;
        emit operationStateChanged();
    }
}

//非同期処理の応答スロット
void QMLFile::asyncFinished(bool result)
{
    m_operationState = result ? FinishedSuccess : FinishedFail;
    emit operationStateChanged();
    m_operationState = Idle;
}
